package boddaert.philippe.cashGame.io.in;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import boddaert.philippe.cashGame.Game;
import boddaert.philippe.cashGame.GameConfiguration;
import boddaert.philippe.cashGame.GameConfigurationCurrencyType;
import boddaert.philippe.cashGame.io.GameConstant;

public class GameImporter {

	public static List<Game> get(Document document) {
		if (document == null)
			throw new IllegalArgumentException();

		if (!isValid(document))
			throw new IllegalArgumentException();

		List<Game> list = new ArrayList<Game>();

		Element root = (Element) document.getFirstChild();
		NodeList childNodes = root.getChildNodes();
		Element currentGame = null;

		for (int i = 0; i < childNodes.getLength(); i++) {
			currentGame = (Element) childNodes.item(i);
			list.add(tranformToGame(currentGame));
		}
		return list;
	}

	private static Game tranformToGame(Element currentGame) {
		Game game = new Game();

		game.setTitle(currentGame.getAttribute(GameConstant.GAME_TITLE));

		NodeList configurationsGame = currentGame.getChildNodes();
		for (int i = 0; i < configurationsGame.getLength(); i++) {
			game
					.addConfiguration(transformToGameConfiguration((Element) configurationsGame
							.item(i)));
		}

		return game;
	}

	private static GameConfiguration transformToGameConfiguration(
			Element configuration) {
		HashMap<String, String> gameInfo = new HashMap<String, String>();

		NodeList childNodes = configuration.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Element element = (Element) childNodes.item(i);
			gameInfo.put(element.getNodeName(), element.getTextContent());
		}

		GameConfiguration configGame = new GameConfiguration(configuration
				.getAttribute(GameConstant.SITE), GameConfigurationCurrencyType.get(gameInfo
				.get(GameConstant.GAME_TYPE)));
		configGame.setBestPrice(Double.parseDouble(gameInfo
				.get(GameConstant.GAME_BEST_PRICE)));
		configGame.setNumberNewAvailable(Integer.parseInt(gameInfo
				.get(GameConstant.GAME_NUMBER_NEW)));
		configGame.setNumberSecondHandAvailable(Integer.parseInt(gameInfo
				.get(GameConstant.GAME_NUMBER_SECOND_HAND)));
		configGame.setUrl(gameInfo.get(GameConstant.GAME_URL));

		return configGame;
	}

	private static boolean isValid(Document document) {
		if (!document.hasChildNodes())
			return false;
		return (GameConstant.GAMES_ROOT.equals(document.getChildNodes().item(0)
				.getNodeName()));
	}

}
